<template>
	<view class="wrap">
		<u-navbar :custom-back="$back" :back-icon-color="navbar.titleColor" is-back :title="navbar.title"
			:background="navbar.background" :title-color="navbar.titleColor">
		</u-navbar>
		<view class="content">
			<uni-section title="访客邀约" type="line">
				<view class="example">
					<!-- 基础表单校验 -->
					<uni-forms ref="valiForm" :rules="rules" label-position="top" :modelValue="valiFormData" label-width="120px">
						<uni-forms-item label="申请来访日期" required name="visitDate">
							<uni-datetime-picker
											type="date"
											:value="valiFormData.visitDate"
											:start="visitDateStart"
											:end="visitDateEnd"
											@change="visitDateChange"
										/>
						</uni-forms-item>
						<uni-forms-item label="来访时间点" required name="visitTimePoint">
							<uni-combox :candidates="candidates" placeholder="请选择时间点" v-model="valiFormData.visitTimePoint"></uni-combox>
						</uni-forms-item>
						<view v-for="item,index in valiFormData.visitorList">
							<view style="border: 1px solid #e0e0e0;margin-bottom: 5px;"></view>
							<view style="text-align: right;">
								<button v-if="valiFormData.visitorList.length != 1" @click.stop.prevent="delVisit(item,index)"
									style="margin-right: 0;line-height:2;" type="warn" size="mini">删除</button>
							</view>
							<uni-forms-item label="来访人名称" required>
								<view class="input-box">
									<u-input class="el-input" v-model="item.visitName" type="text" :border="false" placeholder='请输入来访人名称' :clearable='true'></u-input>
								</view>
							</uni-forms-item>
							<uni-forms-item label="来访人电话" required>
								<view class="input-box">
									<u-input class="el-input" v-model="item.visitPhone" type="text" :border="false" placeholder='请输入来访人电话' :clearable='true'></u-input>
								</view>
							</uni-forms-item>
							<uni-forms-item label="来访人证件号">
								<view class="input-box">
									<u-input class="el-input" v-model="item.visitorCardNo" type="text" :border="false" placeholder='请输入来访人证件号' :clearable='true'></u-input>
								</view>
							</uni-forms-item>
							<uni-forms-item label="上传人脸" name="attachmentTemp">
								<uni-file-picker :key="index" :limit='1' v-model="imageValue" @select="(files) => select(files, index)" @progress="progress" @success="success"
									@fail="fail" @delete="(e) => deleteFile(e, index)"></uni-file-picker>
							</uni-forms-item>
						</view>
						<button type="primary" @click="addVisit">添加来访人</button>
						
						<uni-forms-item label="被访人名称" required name="visitPersonName" class="account">
							<view class="input-box">
								<u-input class="el-input" v-model="valiFormData.visitPersonName" type="text" :border="false" placeholder='请输入被访人名称' :clearable='true'></u-input>
							</view>
						</uni-forms-item>
						<uni-forms-item label="被访人电话" required name="visitPersonPhone">
							<view class="input-box">
								<u-input class="el-input" v-model="valiFormData.visitPersonPhone" type="text" :border="false" placeholder='请输入被访人电话' :clearable='true'></u-input>
							</view>
						</uni-forms-item>
						<uni-forms-item label="来访人数" required name="visitorNumber">
							<view class="input-box">
								<u-input class="el-input" v-model="valiFormData.visitorNumber" type="text" :border="false" placeholder='请输入来访人数' :clearable='true'></u-input>
							</view>
						</uni-forms-item>
						<uni-forms-item label="来访事由" required name="visitSubjectMatter">
							<view class="input-box">
								<u-input class="el-input" v-model="valiFormData.visitSubjectMatter" type="textarea" :border="false" placeholder='请输入来访事由' :clearable='true'></u-input>
							</view>
						</uni-forms-item>
						<uni-forms-item label="来访车牌号" name="visitCarNo" class="forms-item">
							<view class="input-box">
								<u-input class="el-input" v-model="valiFormData.visitCarNo" type="text" :border="false" placeholder='请输入来访车牌号' :clearable='true'></u-input>
							</view>
						</uni-forms-item>
						<uni-forms-item label="拜访位置" name="visitRoomName">
							<view class="input-box">
								<u-input class="el-input" v-model="valiFormData.visitRoomName" type="textarea" :border="false" placeholder='请输入拜访位置' :clearable='true'></u-input>
							</view>
						</uni-forms-item>
						<uni-forms-item label="可到访区域" name="visitorRegion">
							<checkbox-group @change="visitorRegionChange">
							    <view v-for="(item, index) in visitorRegionList" :key="index" class="checkbox-item" style="margin: 1%;float: left;width: 45%;">
							        <checkbox :value="item.value" :checked="item.checked"></checkbox>
							        <text style="margin-left: 30upx;">{{ item.label }}</text>
									<!-- 如果需要每两个复选框之间有空行，可以在这里添加条件渲染的<view> -->
							        <!-- <view v-if="index != 0 && index % 2 == 0" style="height: 50upx;"></view> -->
							    </view>
							</checkbox-group>
						</uni-forms-item>
					</uni-forms>
					<button type="primary" @click="submit('valiForm')">提交</button>
				</view>
			</uni-section>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				candidates: ['全天','上午', '下午'],
				imageValue: [],
				//头部标题配置
				navbar: {
					title: "录入预约申请",
					background: {
						backgroundColor: '#2373FA',
					},
					titleColor: "#ffffff",
				},
				// 校验表单数据
				valiFormData: {
					visitorList: [
						{
							visitName: undefined,
							visitPhone: undefined,
							visitorCardNo: '',
						}
					],
					visitorListJSON: '',
					fileList: [''],
					visitName: undefined,
					visitPhone: undefined,
					visitDate: undefined,
					visitTimePoint: '',
					visitPersonName: undefined,
					visitPersonPhone: undefined,
					visitorNumber: undefined,
					visitSubjectMatter: undefined,
					visitorCardNo: '',
					visitCarNo: '',
					visitRoomName:  '',
					visitorRegion: ''
				},
				// 校验规则
				rules: {
					visitDate: {
						rules: [{
							required: true,
							errorMessage: '申请来访日期不能为空'
						}]
					},
					visitTimePoint: {
						rules: [{
							required: true,
							errorMessage: '来访时间点不能为空'
						}]
					},
					visitName: {
						rules: [{
							required: true,
							errorMessage: '来访人名称不能为空'
						}]
					},
					visitPhone: {
						rules: [{
								required: true,
								errorMessage: '来访人电话不能为空'
							},
							{
								pattern: /^1\d{10}$/,
								errorMessage: '来访人电话格式不正确'
							}
						],
					},
					visitPersonName: {
						rules: [{
							required: true,
							errorMessage: '拜访人名称不能为空'
						}]
					},
					visitPersonPhone: {
						rules: [{
								required: true,
								errorMessage: '拜访人电话不能为空'
							}
						],
					},
					visitorNumber: {
						rules: [{
							required: true,
							errorMessage: '来访人数不能为空'
						}]
					},
					visitSubjectMatter: {
						rules: [{
							required: true,
							errorMessage: '来访事由不能为空'
						}]
					},
				},
				dataTree: [],
				visitorRegionList: [],
				visitDateStart: '',
				visitDateEnd: '',
			}
		},
		onLoad(option) {
			// 申请来访时间当前时间开始计算一年
			this.visitDateStart = this.getCurrentDateString(null,null,null);
			this.visitDateEnd = this.getCurrentDateString(1,null,null);
			this.getVisitorRegion();
		},
		onReady() {},
		methods: {
			getCurrentDateString(addYear,addMonth,addDay) {
			    var currentDate = new Date();
			    var year = currentDate.getFullYear();
			    var month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
			    var day = currentDate.getDate().toString().padStart(2, '0');
				if(addYear != null){
					year += addYear;
				}
				if(addMonth != null){
					month += addMonth;
				}
				if(addDay != null){
					day += addDay;
				}
			    return `${year}-${month}-${day}`;
			},
			visitorRegionChange(e) {
				if(e.detail.value.length > 0){
					this.valiFormData.visitorRegion = e.detail.value.join(",");
				}else{
					this.valiFormData.visitorRegion = '';
				}
			  console.log('checkbox发生change事件，携带value值为：', e.detail.value);
			  // 这里可以根据 e.detail.value 来获取用户选择的结果
			  // e.detail.value 是一个数组，包含了所有被选中的 checkbox 的 value 值
			  this.visitorRegionList = this.visitorRegionList.map(item => {
				return {
				  ...item,
				  checked: e.detail.value.includes(item.value)
				};
			  });
			},
			getVisitorRegion(){
				this.$u.api.visitor.getRegionAll().then(res => {
					res.rows && this.visitorRegionList.push(...res.rows.map(d => {
						return {
							label: d.regionName,
							value: d.id + '',
							checked: false
						}
					}))
				})
			},
			addVisit() {
				var visitorList = this.valiFormData.visitorList;
				visitorList.push({
					visitName: undefined,
					visitPhone: undefined,
					visitorCardNo: '',
				});
				this.valiFormData.visitorList = visitorList
				// 文件
				var fileList = this.valiFormData.fileList;
				fileList.push('');
				this.valiFormData.fileList = fileList
				this.valiFormData.visitorNumber = 1
			},
			delVisit(item,index) {
				var visitorList = this.valiFormData.visitorList;
				visitorList.splice(index, 1);
				this.valiFormData.visitorList = visitorList
				// 文件
				var fileList = this.valiFormData.fileList;
				fileList.splice(index, 1);
				this.valiFormData.fileList = fileList
			},
			visitDateChange(e) {
				this.valiFormData.visitDate = e;
			},
			deleteFile(e,index){
				console.log('deleteFile1：', e)
				console.log('deleteFile2：', index)
				this.valiFormData.fileList[index] = ''
			},
			// 获取上传状态
			select(e,index) {
				console.log('select1：', e)
				console.log('select2：', index)
				this.valiFormData.fileList[index] = e.tempFiles[0].file
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功')
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			returnBack(){
				uni.navigateBack({
				  delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页。
				});
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					const filePath = this.valiFormData.attachmentTemp ? this.valiFormData.attachmentTemp.path : ""
					if(this.valiFormData.visitorList.length == 0){
						uni.showToast({
							title: '至少有一条数据',
							icon: "error"
						})
						return;
					}
					let visitorDataArray = []; // 创建一个空数组来存储每个访问者的数据
					
					let visitorList = this.valiFormData.visitorList;
					let fileList = this.valiFormData.fileList;
					for (var i = 0; i < visitorList.length; i++) {
						let valiFormData = JSON.parse(JSON.stringify(this.valiFormData));
						valiFormData.visitName = visitorList[i].visitName;
						valiFormData.visitPhone = visitorList[i].visitPhone;
						valiFormData.visitorCardNo = visitorList[i].visitorCardNo;
						console.log('visitorList',visitorList[i]);
						valiFormData.attachmentTemp = fileList[i];
						const fileName = valiFormData.attachmentTemp ? 'attachmentTemp' : 'file'
						console.log('valiFormData.attachmentTemp',valiFormData.attachmentTemp);
						if(valiFormData.attachmentTemp){
							uni.uploadFile({
								url: `${this.vuex_config.baseUrl}/visitor/visitorInfo/insert`,
								header: {
									"Authorization": this.vuex_token
								},
								filePath: valiFormData.attachmentTemp.path,
								name: fileName,
								formData: valiFormData,
								success: (response) => {
									let data = JSON.parse(response.data);
									if (data.code == 500) {
										uni.showModal({
											title: '提示',//标题
											content: data.msg,//提示内容
											showCancel: false//不显示取消按钮
										})
										return
									}
									uni.showToast({
										title: `新增成功`,
									})
									setTimeout(() => {
										this.returnBack()
									}, 500)
								},
								fail(err) {
									console.log('err',err);
									uni.showToast({
										title: `${err.errMsg}`,
										icon: "error",
										duration: 5000
									})
									
								}
							});
						}else {
							console.log('wscwj');
							uni.request({
							  url: `${this.vuex_config.baseUrl}/visitor/visitorInfo/insert`,
							  method: 'POST',
							  data: valiFormData,
							  header: {
							    'content-type': 'application/x-www-form-urlencoded', // 如果你发送的是表单数据，可以这样设置
							    // 或者如果你发送的是 JSON 数据，可以这样设置
							    // 'content-type': 'application/json'
							    // 并且在 data 中发送 JSON.stringify(yourObject)
								"Authorization": this.vuex_token
							  },
							  success: (response) => {
							    // 处理响应数据
								let data = response.data;
								if (data.code == 500) {
									uni.showModal({
										title: '提示',//标题
										content: data.msg,//提示内容
										showCancel: false//不显示取消按钮
									})
									return
								}
								uni.showToast({
									title: `新增成功`,
								})
								setTimeout(() => {
									this.returnBack()
								}, 500)
							  },
							  fail: (err) => {
							    console.error('err:', err);
							    // 处理请求失败的情况
								uni.showToast({
									title: `${err.errMsg}`,
									icon: "error",
									duration: 5000
								})
								
							  }
							});
						}
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: #f2f4f8;
	}
	/deep/.uni-checkbox-input-checked {
		background-color: #1766f8 !important;
	}
	.input-box {
		border: 1rpx solid #bbb;
		align-items: center;
		border-radius: 5rpx;
		width: 100%;
		padding-left: 20rpx;
	}
	.wrap {
		padding-bottom: 100upx;
		overflow: hidden;

		/deep/.uni-section-header {
			display: none;
		}

		.content {
			.example {
				padding: 15px;
				background-color: #fff;
			}
			

			.segmented-control {
				margin-bottom: 15px;
			}

			.button-group {
				margin-top: 15px;
				display: flex;
				justify-content: space-around;
			}

			.form-item {
				display: flex;
				align-items: center;
			}

			.button {
				display: flex;
				align-items: center;
				height: 35px;
				margin-left: 10px;
			}
		}
	}
</style>